let targetTime = new Date(0);
let g_PitchAngleMax=10,g_PitchAngleMin=-10,g_RotateAngleMax=90,g_RotateAngleMin=-90,g_DCMoveMiMax=300,g_DCMoveMiMin=0;
let subVal = 0;
let bConfirmNoticeShow = false;
let strNotDisappearNotice = "";
let lasStrNotDisappearNotice = "";
let bCanSwitchToCoalYardShow = false;
let arrDLCurrent = [];
let arrJMFlow= [];
let lastDLTimeValue = "";
let lastPDLLTimeValue = "";
let flowWS = null;
let NDData= [];
let bNotifyLoading = false;
let m_NeptWebSocket = null;
let qlbLastRotateValue = "";
let dlbLastRotateValue = "";
let gbjLastRotateValue = "";
let rotateTag = false;

let gzTable = [];
let gzInfo = [];
gzInfo.push('故障名称');
gzInfo.push("时间");
gzTable.push(gzInfo);

Notiflix.Notify.init({
    widt:'500px',
    fontSize:'22px',
    timeout: g_NotiflixTimeout
});

Notiflix.Confirm.init({
    width: '620px'
});

// 发送Post消息
function sendPostMessage(serverUrl, request) {
    if (serverUrl == null) {
        return;
    }
    if (request == null) {
        return;
    }
    fetch(serverUrl, {
        method: 'post',
        body: JSON.stringify(request),
        headers: { 'Content-Type': 'application/json' }
    }).then((e) => {
        e.text().then(data => {
           let jdata = JSON.parse(data);
            if(jdata.Code == g_ResCodeSuccess) {
                Notiflix.Notify.success('成功!');
            }
            else {
                Notiflix.Notify.warning(jdata.Message);
            }
        });
    });
}

function onExecuteSingleAction(actionId,btnValue,type) {
    if (actionId == null || actionId == ""){
        Notiflix.Notify.warning('该动作名称为空');
    }
    //直接生效
    if(type == 0){
        if(actionId == "FaultReset"){
            var currentTime = new Date().getTime(); // 3秒后的当前时间戳
            var elapsedTime = currentTime - targetTime; // 计算时间差
            // 判断时间差是否超过3000毫秒（即3秒）
            if (elapsedTime > 3000) {
                dkSubmit(actionId);
                targetTime = new Date().getTime();
            } else {
                Notiflix.Notify.failure('操作间隔小于3秒,请勿连续点击!');
            }
        }
        else{
            // 停止，直接生效
            dkSubmit(actionId);
        }
    }
    else{
        Notiflix.Confirm.show(
            '提示',
            '确定执行 ' + btnValue + ' 的操作吗？',
            '确认',
            '取消',
            () => {
                dkSubmit(actionId);
            },
            () => {
                
            }
        );
    }
}


//单控提交
function dkSubmit(actionId) {
    let request = {};
    request.Function = "ExecuteSingleAction";
    request.Action = actionId;
    sendPostMessage(g_ManualHttUrl, request);
}

// 辅机控制
function AuxiliaryCMD(obj, cmd,optName){
    let requestParam = {
        "cmdType": "AUXILIARY_EXECUTE",
        "Cmd": cmd,
        "Obj": obj,
        "OptName": optName
    };

    $.confirm({
        theme: 'Material',
        type: 'blue',
        title: optName + ' 操作',
        content: '确定执行 ' + optName + ' 的操作吗？',
        buttons: {
            执行: {
                btnClass: 'btn-blue',
                action: function () {
                    $.ajax({
                        async: true,
                        data: JSON.stringify(requestParam),
                        dataType: "json",
                        type: "POST",
                        url: g_CenterHttpUrl,
                
                        success: function(rsp){
                            if (rsp["resCode"] == g_ResCodeSuccess){
                                Notiflix.Notify.success('命令已下发' + optName + '动作成功');
                            }
                            else {
                                Notiflix.Notify.warning("执行操作失败：" + rsp["resMsg"]);
                            }
                        },
                        error: function(rsp){
                            Notiflix.Notify.failure("服务端异常!");
                        }
                    });
                }
            },

            取消: {
                btnClass: 'btn-orange'
            }
        }
    });
}

// 点击运动到
function onClickMoveTo(actionId, val, btnValue) {
    let unit = '度';
    if (val == '' || val == null) {
        Notiflix.Notify.warning("请输入需要运动到的具体的值！");
        return;
    }

    let fVal = parseFloat(val);
    if(fVal.toString() == 'NaN'){
        Notiflix.Notify.warning("请输入正确的数字格式!");
        return;
    }
    if (actionId == "CombineGBJPitchTo") {
        if ((fVal < g_PitchAngleMin) || (fVal > g_PitchAngleMax)) {
            Notiflix.Notify.warning( '请输入 ' + g_PitchAngleMin + ' 至 ' + g_PitchAngleMax + ' 之间的值');
            return;
        }
    }
    else if(actionId == "CombineQLBRotateTo" || actionId == "CombineDLBRotateTo") {
        if ((fVal < 0) || (fVal > 360)) {
            Notiflix.Notify.warning( '请输入 0 至 360 之间的值');
            return;
        }
    }

    let strContent = btnValue + val + unit;
    Notiflix.Confirm.show(
        '提示',
        '确定执行 ' + strContent + ' 的操作吗？',
        '确认',
        '取消',
        () => {
            onExecuteCombineAction(actionId,val);
        },
        () => {
            
        }
    );
}

// 执行复合动作
function onExecuteCombineAction(actionId, target) {
    let request = {};
    request.Function = "ExecuteCombineAction";
    request.Action = actionId;
    request.Target = target;
    sendPostMessage(g_ManualHttUrl, request);
}

// 开始取料任务
function onStartQLTask(qlMode) {
    let request = {};
    request.Function = "Start";
    request.LeftBoundary = 190;
    request.RightBoundary = 210;
    request.RotationDirection = 2;
    request.Mode = qlMode;
    request.PitchDownFirst = 0;
    sendPostMessage(g_QLTaskHttUrl, request);
}

// 暂停取料任务
function onPauseQLTask() {
    let request = {};
    request.Function = "Pause";
    sendPostMessage(g_QLTaskHttUrl, request);
}

// 恢复取料任务
function onResumeQLTask() {
    let request = {};
    request.Function = "Resume";
    sendPostMessage(g_QLTaskHttUrl, request);
}

// 改变取料任务的内容
function onChangeQLContent(changedContent, changedValue) {
    let request = {};
    request.Function = "ChangeContent";
    request.ChangedContent = changedContent;
    request.ChangedValue = changedValue;
    sendPostMessage(g_QLTaskHttUrl, request);
}

// 结束取料任务
function onStopQLTask() {
    let request = {};
    request.Function = "Stop";
    sendPostMessage(g_QLTaskHttUrl, request);
}

// 开始堆料任务
function onStartDLTask() {
    let request = {};
    request.Function = "Start";
    request.LeftBoundary = 30;
    request.RightBoundary = 40;
    request.RotationDirection = 2;
    request.Mode = 1;
    request.CoalTargetHeight = 30;
    // request.CoalPileId = "0701";
    // request.RotationAngle = 30;
    sendPostMessage(g_DLTaskHttUrl, request);
}

// 暂停堆料任务
function onPauseDLTask() {
    let request = {};
    request.Function = "Pause";
    sendPostMessage(g_DLTaskHttUrl, request);
}

// 恢复堆料任务
function onResumeDLTask() {
    let request = {};
    request.Function = "Resume";
    sendPostMessage(g_DLTaskHttUrl, request);
}

// 结束堆料任务
function onStopDLTask() {
    let request = {};
    request.Function = "Stop";
    sendPostMessage(g_DLTaskHttUrl, request);
}

// 改变堆料任务的内容
function onChangeDLContent(changedContent, changedValue) {
    let request = {};
    request.Function = "ChangeContent";
    request.ChangedContent = changedContent;
    request.ChangedValue = changedValue;
    sendPostMessage(g_DLTaskHttUrl, request);
}

// 登出
function onLogout() {
    let request = {};
    request.Function = "LogOut";
    sendPostMessage(g_CenterHttpUrl, request);
    window.open("http://localhost:8001/wrzs_nd/login","_self");
    // meta2d.setValue({ id: 'iframeUrl', iframe: "/wrzs_nd/login" });
}

// 更新页面：截面流量数据
function updateJMFlow(fValue) {
    let fLastPDCFlow = fValue;
    if (fLastPDCFlow < 0) {
        fLastPDCFlow = 0;
    }

    let NowTime = new Date();
    let TimeValue = NowTime.getFullYear() + "-" +
        NowTime.getMonth() + "-" +
        NowTime.getDate() + " " +
        NowTime.getHours() + ":" +
        NowTime.getMinutes() + ":" +
        NowTime.getSeconds();
    let NewData = {
        name: NowTime.toString(),
        value: [
            TimeValue,
            fLastPDCFlow
        ]
    };

    // arrJMFlow.push(NewData);
    if (lastPDLLTimeValue != TimeValue) {
        arrJMFlow.push(NewData);
    }
    if (arrJMFlow.length > g_EchartDataMaxLength) {
        arrJMFlow.shift();
    }
    lastPDLLTimeValue = TimeValue;
    meta2d.setValue({
        id: 'pdll',
        'echarts.option.series.0.data': arrJMFlow
    });
    // meta2d.setValue({
    //     id: 'pdFlow',text: fValue
    // });
}

// 更新页面：刮板机电流
function updateGBJCurrent(fValue) {
    let fLastDLCurrent = fValue;
    if (fLastDLCurrent <= g_DLCurrentIgnore) {
        fLastDLCurrent = 0;
    }

    let NowTime = new Date();
    let TimeValue = NowTime.getFullYear() + "-" +
        NowTime.getMonth() + "-" +
        NowTime.getDate() + " " +
        NowTime.getHours() + ":" +
        NowTime.getMinutes() + ":" +
        NowTime.getSeconds();
    let NewData = {
        name: NowTime.toString(),
        value: [
            TimeValue,
            fLastDLCurrent
        ]
    };

    // arrDLCurrent.push(NewData);
    if (lastDLTimeValue != TimeValue) {
        arrDLCurrent.push(NewData);
    }

    if (arrDLCurrent.length > g_EchartDataMaxLength) {
        arrDLCurrent.shift();
    }
    lastDLTimeValue = TimeValue;
    meta2d.setValue({
        id: 'gbjCurrent',
        'echarts.option.series.0.data': arrDLCurrent
    });
    meta2d.setValue({
        id: 'gbjCurrent',text: fValue.toFixed(2)
    });
}

function isPositiveNegativeNumber(value) {
    return  /^[+-]?\d+(\.\d{1,2})?$/.test(value);
}

// 更新页面：通知消息
function updateNotice(jsData) {
    if ((jsData == null) || (jsData == "")) {
        return;
    }

    if ((jsData.PT != null) && (jsData.PT != "")) {
        let dataNotice = [];
        // 主页面固定区域显示通知消息
        if (strNotDisappearNotice == "") {
            strNotDisappearNotice = jsData.PT;
            dataNotice.push(jsData.PT);
        }
        else {
            if(lasStrNotDisappearNotice != jsData.PT){
                dataNotice.push(jsData.PT);
            }
        }
        if(dataNotice.length > 0){
            NDData.unshift(dataNotice);
        }
        //大于最大长度,则删除一个数据
        if(NDData.length > g_NoticeScrollHeightMax){
            NDData.pop();
        }
        meta2d.setValue({ id: 'notice', data: NDData,vline:true});
        // meta2d.setValue({ id: 'notice', lineHeight: 1 });
        lasStrNotDisappearNotice = jsData.PT;
        // textArea.scrollTop = textArea.scrollHeight;
    }

    if ((jsData.TM != null) && (jsData.TM != "")) {
        // 显示几秒后即自动消失的通知消息
        Notiflix.Notify.info(jsData.TM);
    }

    if ((!bConfirmNoticeShow) && (jsData.CF != null) && (jsData.CF != "")) {
        // 弹出框，需要用户点击确认或取消的通知消息
        bConfirmNoticeShow = true;
        ShowConfirmNotice(jsData.CF);
    }
}

// 更新页面：通知消息
function updateADNotice(jsData) {
    if ((jsData == null) || (jsData == "")) {
        return;
    }

    // 主页面固定区域显示通知消息
    if (strNotDisappearNotice == "") {
        strNotDisappearNotice = jsData;
    }
    else {
        if(lasStrNotDisappearNotice != jsData){
            // strNotDisappearNotice += ("\r\n" + jsData.ND);
            strNotDisappearNotice = ("\r\n" + "") + strNotDisappearNotice;
            strNotDisappearNotice =jsData + ("\r\n" + strNotDisappearNotice);
        }
    }

    let textArea = meta2d.findOne('notice');
    let taScrollHeight = textArea.height;
    if (taScrollHeight > g_NoticeScrollHeightMax) {
        let nIndex = strNotDisappearNotice.indexOf("\n");
        strNotDisappearNotice = strNotDisappearNotice.substring(nIndex + 1);
    }
    // textArea.text = strNotDisappearNotice;

    meta2d.setValue({ id: 'notice', text: strNotDisappearNotice});
    meta2d.setValue({ id: 'notice', lineHeight: 1 });
    lasStrNotDisappearNotice = jsData;
    // textArea.scrollTop = textArea.scrollHeight;
}

//判断故障是否已经在故障表格里
function isInErrorTable(name,table){
    if(table.find(function(info) {
        return info[0] == name;
    }) != undefined){
        return true;
    }else{
        return false;
    }
}

//去除已经在故障表格里的故障
function removeErrorInErrorTable(name,table){
   return table.filter(function(subArray) {
        return !subArray.includes(name);
    });
}

//故障处理
function errorTable(data){
    let gzInfo = [];
   if(data.id.indexOf('GZ') > 0 || data.id.indexOf('WTKY') > 0 || data.id.indexOf('Z_ERR') > 0 || data.id.indexOf('JLJY_TZLC') > 0){
        var name = getErrorLabel(data.id);
        switch (data.value) {
            case 1:
                if(!isInErrorTable(name,gzTable)){
                    gzInfo.push(name);
                    gzInfo.push(getNowTime());
                }
                break;
            default:
                gzTable = removeErrorInErrorTable(name,gzTable);
        }
    }

    if(gzInfo.length != 0){
        gzTable.push(gzInfo);
    }
    
    meta2d.setValue({id:'gzTable',data:gzTable});
}

// 显示需确认或取消的弹窗通知消息
function ShowConfirmNotice(confirmData) {
    // bConfirmNoticeShow = true;
    // bConfirmNoticeShow = false;
    let strKey = confirmData.Key;
    let strType = confirmData.PointType;
    // let confirmFunc = function () {
    //     autoLocateButtonEnabled();
    //     let request = {};
    //     request.cmdType = "NoticeResponse";
    //     request.Key = strKey;
    //     request.Click = "Confirm";

    //     $.ajax({
    //         async: true,
    //         data: JSON.stringify(request),
    //         dataType: "json",
    //         type: "POST",
    //         url: g_CenterHttpUrl,

    //         success: function (rsp) {
    //             bConfirmNoticeShow = false;
    //             if (rsp["resCode"] == g_ResCodeSuccess) {
    //                 Notiflix.Notify.info("已确认");
    //             }
    //             else {
    //                 Notiflix.Notify.warning(rsp["resMsg"]);
    //             }
    //         },

    //         error: function (rsp) {
    //             bConfirmNoticeShow = false;
    //             Notiflix.Notify.failure(' 操作执行异常');
    //         }
    //     });
    // };

    if (strType == "1") {
        // 只有确认按钮
        // $.alert({
        //     boxWidth: '350px',
        //     useBootstrap: false,
        //     draggable: true,
        //     backgroundDismiss: true,
        //     theme: 'Material',
        //     type: 'red',
        //     title: '服务端通知消息',
        //     content: confirmData.Content,
        //     timeout: 5000,
        //     buttons: {
        //         确认: {
        //             btnClass: 'btn-blue',
        //             action: ''
        //         }
        //     },
        //     onClose: function () {
        //         bConfirmNoticeShow = false;
        //     }
        // });
        // // autoClose:true,

        Notiflix.Loading.arrows(confirmData.Content,{
            clickToClose: true,
            messageFontSize: '20px',
        });
        bNotifyLoading = true;
    }
    else if (strType == "2") {
        // 有确认和取消按钮
        Notiflix.Confirm.init({
            width: '620px'
        });
        Notiflix.Confirm.show(
            '服务端通知消息',
            confirmData.Content,
            '确认',
            '取消',
            () => {
                autoLocateButtonEnabled();
                let request = {};
                request.cmdType = "NoticeResponse";
                request.Key = strKey;
                request.Click = "Confirm";

                $.ajax({
                    async: true,
                    data: JSON.stringify(request),
                    dataType: "json",
                    type: "POST",
                    url: g_CenterHttpUrl,

                    success: function (rsp) {
                        bConfirmNoticeShow = false;
                        if (rsp["resCode"] == g_ResCodeSuccess) {
                            Notiflix.Notify.info("已确认");
                        }
                        else {
                            Notiflix.Notify.warning(rsp["resMsg"]);
                        }
                    },

                    error: function (rsp) {
                        bConfirmNoticeShow = false;
                        Notiflix.Notify.failure(' 操作执行异常');
                    }
                });
            },
            () => {
                autoLocateButtonEnabled();
                let request = {};
                request.cmdType = "NoticeResponse";
                request.Key = strKey;
                request.Click = "Cancel";

                $.ajax({
                    async: true,
                    data: JSON.stringify(request),
                    dataType: "json",
                    type: "POST",
                    url: g_CenterHttpUrl,

                    success: function (rsp) {
                        bConfirmNoticeShow = false;
                        if (rsp["resCode"] == g_ResCodeSuccess) {
                            Notiflix.Notify.info("已取消");
                        }
                        else {
                            Notiflix.Notify.warning(rsp["resMsg"]);
                        }
                    },

                    error: function (rsp) {
                        bConfirmNoticeShow = false;
                        Notiflix.Notify.failure(' 操作执行异常');
                    }
                });
            }
        );
        
    }else if (strType == "3") {
        // 取消按钮
        $.alert({
            boxWidth: '350px',
            useBootstrap: false,
            draggable: true,
            backgroundDismiss: true,
            theme: 'Material',
            type: 'red',
            title: '服务端通知消息',
            content: confirmData.Content,
            buttons: {
                取消: {
                    btnClass: 'btn-NOTorange',
                    action: function () {
                        let request = {};
                        request.cmdType = "NoticeResponse";
                        request.Key = strKey;
                        request.Click = "Cancel";

                        $.ajax({
                            async: true,
                            data: JSON.stringify(request),
                            dataType: "json",
                            type: "POST",
                            url: g_CenterHttpUrl,

                            success: function (rsp) {
                                bConfirmNoticeShow = false;
                                if (rsp["resCode"] == g_ResCodeSuccess) {
                                    Notiflix.Notify.info("已取消");
                                }
                                else {
                                    Notiflix.Notify.warning(rsp["resMsg"]);
                                }
                            },

                            error: function (rsp) {
                                bConfirmNoticeShow = false;
                                Notiflix.Notify.failure(' 操作执行异常');
                            }
                        });
                    }
                }
            },

            onClose: function () {
                bConfirmNoticeShow = false;
            }
        });
    }
}

// 点击自动定位
function OnClickAutoLocate(locationType) {
    const request = {};
    request.Function = "StartAutoLocation";
    request.cmdType = "StartAutoLocation";
    // request.LocationType = locationType;
    request.DCPosition = meta2d.findOne('dcMoveToValue').text;
    request.XBRotationAngle = meta2d.findOne('rotateMoveToValue').text;
    request.XBPitchAngle = meta2d.findOne('pitchMoveToValue').text;
    $.ajax({
        url: g_CenterHttpUrl,
        contentType: 'application/json',
        data: JSON.stringify(request),
        async: true,
        type: "post",
        dataType: "json",
        success: function (rsp) {
            if (rsp["resCode"] == g_ResCodeSuccess) {
                Notiflix.Notify.success("操作执行成功!");
            } else {
                Notiflix.Notify.failure("操作执行失败：" + rsp["resMsg"]);
            }
        },
        error: function (rsp) {
            Notiflix.Notify.failure("自动定位异常!");
        }
    });
}

// 结束自动定位
function OnClickStopAutoLocate() {
    const request = {};
    request.Function = "StopAutoLocation";
    request.cmdType = "StopAutoLocation";
    $.ajax({
        url: g_CenterHttpUrl,
        contentType: 'application/json',
        data: JSON.stringify(request),
        async: true,
        type: "post",
        dataType: "json",
        success: function (rsp) {
            if (rsp["resCode"] == g_ResCodeSuccess) {
                Notiflix.Notify.success("操作执行成功!");
            } else {
                Notiflix.Notify.failure("操作执行失败：" + rsp["resMsg"]);
            }
        },
        error: function (rsp) {
            Notiflix.Notify.failure("自动定位异常!");
        }
    });
}

// 点击自动回正
function OnClickAutoReturn() {
    const request = {};
    request.cmdType = "StartAutoLocation";
    request.LocationType = 0;
    autoLocateButtonDisabled();
    $.ajax({
        url: g_CenterHttpUrl,
        contentType: 'application/json',
        data: JSON.stringify(request),
        async: true,
        type: "post",
        dataType: "json",
        success: function (rsp) {
            if (rsp["resCode"] == g_ResCodeSuccess) {
                Notiflix.Notify.success("操作执行成功!");
            } else {
                Notiflix.Notify.failure("操作执行失败：" + rsp["resMsg"]);
                autoLocateButtonEnabled();
            }
        },
        error: function (rsp) {
            Notiflix.Notify.failure("自动定位异常!");
            autoLocateButtonEnabled();
        }
    });
}

// 结束自动回正
function OnClickStopAutoReturn() {
    const request = {};
    request.cmdType = "StopAutoLocation";
    autoLocateButtonEnabled();
    $.ajax({
        url: g_CenterHttpUrl,
        contentType: 'application/json',
        data: JSON.stringify(request),
        async: true,
        type: "post",
        dataType: "json",
        success: function (rsp) {
            if (rsp["resCode"] == g_ResCodeSuccess) {
                Notiflix.Notify.success("操作执行成功!");
            } else {
                Notiflix.Notify.failure("操作执行失败：" + rsp["resMsg"]);
                autoLocateButtonEnabled();
            }
        },
        error: function (rsp) {
            Notiflix.Notify.failure("自动定位异常!");
            autoLocateButtonEnabled();
        }
    });
}

// 点击定位并取料
function StartLocationAndQL(locationType) {
    const request = {};
    request.Function = "StartLocationAndQL";
    request.cmdType = "StartLocationAndQL";
    // request.LocationType = locationType;
    request.DCPosition = meta2d.findOne('dcMoveToValue').text;
    request.XBRotationAngle = meta2d.findOne('rotateMoveToValue').text;
    request.XBPitchAngle = meta2d.findOne('pitchMoveToValue').text;
    $.ajax({
        url: g_CenterHttpUrl,
        contentType: 'application/json',
        data: JSON.stringify(request),
        async: true,
        type: "post",
        dataType: "json",
        success: function (rsp) {
            if (rsp["resCode"] == g_ResCodeSuccess) {
                Notiflix.Notify.success("操作执行成功!");
            } else {
                Notiflix.Notify.failure("操作执行失败：" + rsp["resMsg"]);
            }
        },
        error: function (rsp) {
            Notiflix.Notify.failure("定位并取料异常!");
        }
    });
}


// 点击清空皮带流量
function OnClickClearBeltFlow() {
    const request = {};
    request.cmdType = "ClearBeltFlow";
    request.Function = "ClearBeltFlow";
    $.ajax({
        url: g_CenterHttpUrl,
        contentType: 'application/json',
        data: JSON.stringify(request),
        async: true,
        type: "post",
        dataType: "json",
        success: function (rsp) {
            if (rsp["resCode"] == g_ResCodeSuccess) {
                Notiflix.Notify.success("操作执行成功!");
            } else {
                Notiflix.Notify.failure("操作执行失败：" + rsp["resMsg"]);
            }
        },
        error: function (rsp) {
            Notiflix.Notify.failure("清空皮带流量异常!");
        }
    });
}

// 获取页面渲染内容
function onGetPageRenderedContent(pageId) {
    let request = {};
    request.Function = "GetPageRenderedContent";
    request.PageId = pageId;
    sendPostMessage(g_CenterHttpUrl, request);
}

function updateView(message) {
    let jsData = JSON.parse(message);
    if (jsData != null && jsData != "" && jsData != undefined){
        updateViewByInfo(jsData.INFO);
        updateViewByButton(jsData.BUTTON);
        updateViewByTopButton(jsData.TOPBUTTON);
        updateState(jsData.STATE);
        updateQLTask(jsData.QL);
        updateDLTask(jsData.DL);
        updateNotice(jsData.Notice);
        // updateFW(jsData.FW);
        // updateCM(jsData.CM);
    }
}

//更新主体信息
function updateViewByInfo(jsData) {
    if (jsData == null || jsData == "" || jsData == undefined) {
        return;
    }
    for (let item of jsData) {
        if(item.I == "qlbRotateValue" || item.I == "dlbRotateValue" || item.I == "gbjPitchAngle"){
            if(item.I == "qlbRotateValue" && qlbLastRotateValue != item.V){
                meta2d.setValue({ id: item.I, rotate: 90 + parseFloat(item.V) });
                qlbLastRotateValue = item.V;
                // rotateTag = true;
            }else if(item.I == "dlbRotateValue" && dlbLastRotateValue != item.V){
                meta2d.setValue({ id: item.I, rotate: 90 + parseFloat(item.V) });
                dlbLastRotateValue = item.V;
                // if(!rotateTag){
                //     rotateTag = true;
                // }
            }else if(item.I == "gbjPitchAngle" && gbjLastRotateValue != item.V){
                meta2d.setValue({ id: item.I, rotate: 0 - parseFloat(item.V) });
                gbjLastRotateValue = item.V;
            }else{
                rotateTag = false;
            }
            if(rotateTag){
                // setTimeout(()=>{meta2d.scale(meta2d.store.data.scale);},50)
            }
        }else{
            meta2d.setValue({ id: item.I, text: item.V });
            if(item.I == "wheelBucketState" && item.C == "red"){
                if(bNotifyLoading){
                    Notiflix.Loading.remove();
                    bNotifyLoading = false;
                }
            }
            if(item.I == "wheelBucketCurrent"){
                updateGBJCurrent(parseFloat(item.V));
            }
            if(item.I == "xbBeltFlow"){
                updateJMFlow(parseFloat(item.V));
            }
        }
    }
}
//更新按钮信息
function updateViewByButton(jsData) {
    if (jsData == null || jsData == "" || jsData == undefined) {
        return;
    }
    for (let item of jsData) {
        meta2d.setValue({ id: item.I,background: item.C });
    }
}
//更新顶部按钮信息
function updateViewByTopButton(jsData) {
    if (jsData == null || jsData == "" || jsData == undefined) {
        return;
    }
    for (let item of jsData) {
        meta2d.setValue({ id: item.I,textColor: item.C ,activeTextColor:item.C,hoverTextColor:item.C});
    }
}
// 更新页面：取料任务
function updateQLTask(jsData) {
    if (jsData == null || jsData == "" || jsData == undefined) {
        meta2d.setValue({ id: 'qlStartTask', showChild: 0 });
        meta2d.setValue({ id: 'qlPauseTask', showChild: 0 });
        meta2d.setValue({ id: 'qlStopTask', showChild: 1 });
        meta2d.setValue({ id: 'qlState', text: '无任务',textColor: 'white' ,activeTextColor:'white',hoverTextColor:'white'});
        meta2d.setValue({ id: 'qlLeftBoundary', text: "#" });
        meta2d.setValue({ id: 'qlRightBoundary', text: "#" });
        meta2d.setValue({ id: 'qlEachPitchAngle', text: "#" });
    }
    else {
        if(jsData.State == "运行中"){
            meta2d.setValue({ id: 'qlStartTask', showChild: 1 });
        }else{
            meta2d.setValue({ id: 'qlStartTask', showChild: 0 });
        }
        if(jsData.State == "已暂停"){
            meta2d.setValue({ id: 'qlPauseTask', showChild: 1 });
        }else{
            meta2d.setValue({ id: 'qlPauseTask', showChild: 0 });
        }
        if(jsData.State == "已结束"){
            meta2d.setValue({ id: 'qlStopTask', showChild: 1 });
        }else{
            meta2d.setValue({ id: 'qlStopTask', showChild: 0 });
        }
        
        meta2d.setValue({ id: 'qlState', text: jsData.State ,textColor: 'red' ,activeTextColor:'red',hoverTextColor:'red'});
        meta2d.setValue({ id: 'qlLeftBoundary', text: jsData.LeftBoundary });
        meta2d.setValue({ id: 'qlRightBoundary', text: jsData.RightBoundary });
        meta2d.setValue({ id: 'qlEachPitchAngle', text: jsData.EachPitchAngle });
    }
    
}

// 更新页面：堆料任务
function updateDLTask(jsData) {
    if (jsData == null || jsData == "" || jsData == undefined) {
        meta2d.setValue({ id: 'dlStartTask', showChild: 0 });
        meta2d.setValue({ id: 'dlPauseTask', showChild: 0 });
        meta2d.setValue({ id: 'dlStopTask', showChild: 1 });
        meta2d.setValue({ id: 'dlState', text: '无任务' ,textColor: 'white' ,activeTextColor:'white',hoverTextColor:'white'});
        meta2d.setValue({ id: 'dlLeftBoundary', text: "#" });
        meta2d.setValue({ id: 'dlRightBoundary', text: "#" });
        meta2d.setValue({ id: 'dlRotationDirection', text: "#" });
        meta2d.setValue({ id: 'dlCoalHeight', text: "#" });
        meta2d.setValue({ id: 'dlCoalTargetHeight', text: "#" });
        meta2d.setValue({ id: 'dlEachRotationAngle', text: "#" });
    }
    else {
        if(jsData.State == "运行中"){
            meta2d.setValue({ id: 'dlStartTask', showChild: 1 });
        }else{
            meta2d.setValue({ id: 'dlStartTask', showChild: 0 });
        }
        if(jsData.State == "已暂停"){
            meta2d.setValue({ id: 'dlPauseTask', showChild: 1 });
        }else{
            meta2d.setValue({ id: 'dlPauseTask', showChild: 0 });
        }
        if(jsData.State == "已结束"){
            meta2d.setValue({ id: 'dlStopTask', showChild: 1 });
        }else{
            meta2d.setValue({ id: 'dlStopTask', showChild: 0 });
        }
        
        meta2d.setValue({ id: 'dlState', text: jsData.State, textColor: 'red' ,activeTextColor:'red',hoverTextColor:'red' });
        meta2d.setValue({ id: 'dlLeftBoundary', text: jsData.LeftBoundary });
        meta2d.setValue({ id: 'dlRightBoundary', text: jsData.RightBoundary });
        meta2d.setValue({ id: 'dlRotationDirection', text: jsData.RotationDirection });
        meta2d.setValue({ id: 'dlCoalHeight', text: jsData.CoalHeight });
        meta2d.setValue({ id: 'dlCoalTargetHeight', text: jsData.CoalTargetHeight });
        meta2d.setValue({ id: 'dlEachRotationAngle', text: jsData.EachRotationAngle });
    }
}

function updateViewByHtmlB(jsData) {
    if (jsData == null || jsData == "" || jsData == undefined) {
        return;
    }
    for (let item of jsData) {
        meta2d.setValue({ id: item.I, textColor: item.C,activeTextColor:item.C,hoverTextColor:item.C ,text: item.V });
    }
}

//更新圆形状态
function updateState(jsData) {
    if (jsData == null || jsData == "" || jsData == undefined) {
        return;
    }
    //页面中圆点的状态，1是红色，0是绿色
    for (let item of jsData) {
        if (item.V != subVal) {
            subVal = item.V;
        } 
        // meta2d.setValue({ id: item.I, showChild: subVal });

        if(item.I == "dlbRotateStateValue"){
            if(item.V == "1"){
                meta2d.setValue({ id: "dlbRotateLeft", visible: true });
                meta2d.setValue({ id: "dlbRotateStateValue", showChild: 1 });
            }else if(item.V == "2"){
                meta2d.setValue({ id: "dlbRotateRight", visible: true });
                meta2d.setValue({ id: "dlbRotateStateValue", showChild: 1 });
            }else{
                meta2d.setValue({ id: "dlbRotateLeft", visible: false });
                meta2d.setValue({ id: "dlbRotateRight", visible: false });
                meta2d.setValue({ id: "dlbRotateStateValue", showChild: 0 });
            }
        }else if(item.I == "qlbRotateStateValue"){
            if(item.V == "1"){
                meta2d.setValue({ id: "qlbRotateLeft", visible: true });
                meta2d.setValue({ id: "qlbRotateStateValue", showChild: 1 });
            }else if(item.V == "2"){
                meta2d.setValue({ id: "qlbRotateRight", visible: true });
                meta2d.setValue({ id: "qlbRotateStateValue", showChild: 1 });
            }else{
                meta2d.setValue({ id: "qlbRotateLeft", visible: false });
                meta2d.setValue({ id: "qlbRotateRight", visible: false });
                meta2d.setValue({ id: "qlbRotateStateValue", showChild: 0 });
            }
        }
    }
    
}
// 更新页面：精准控制范围
function updateFW(jsData) {
    if (jsData == null || jsData == "" || jsData == undefined) {
        meta2d.setValue({ id: 'upLimitValue', text: 0 });
        meta2d.setValue({ id: 'downLimitValue', text: 0 });
        meta2d.setValue({ id: 'leftInnerLimitValue', text: 0 });
        meta2d.setValue({ id: 'leftLimitValue', text: 0 });
        meta2d.setValue({ id: 'rightLimitValue', text: 0 });
        meta2d.setValue({ id: 'rightInnerLimitValue', text: 0 });
        meta2d.setValue({ id: 'forwardLimitValue', text: 0 });
        meta2d.setValue({ id: 'backLimitValue', text: 0 });
        meta2d.setValue({ id: 'beltDownLimitValue', text: 0 });
        return;
    }
    else {
        g_PitchAngleMax = jsData.XBPitchMax;
        g_PitchAngleMin = jsData.XBPitchMinInCoalArea;
        g_RotateAngleMax = jsData.XBLeftOuterLimit;
        g_RotateAngleMin = jsData.XBRightOuterLimit;
        g_DCMoveMiMax = jsData.DCPositionMax;
        g_DCMoveMiMin = jsData.DCPositionMin;
        meta2d.setValue({ id: 'upLimitValue', text: jsData.XBPitchMax });
        meta2d.setValue({ id: 'downLimitValue', text: jsData.XBPitchMinInCoalArea });
        meta2d.setValue({ id: 'leftInnerLimitValue', text: jsData.XBLeftInnerLimit });
        meta2d.setValue({ id: 'leftLimitValue', text: jsData.XBLeftOuterLimit });
        meta2d.setValue({ id: 'rightLimitValue', text: jsData.XBRightOuterLimit });
        meta2d.setValue({ id: 'rightInnerLimitValue', text: jsData.XBRightInnerLimit });
        meta2d.setValue({ id: 'forwardLimitValue', text: jsData.DCPositionMax });
        meta2d.setValue({ id: 'backLimitValue', text: jsData.DCPositionMin });
        meta2d.setValue({ id: 'beltDownLimitValue', text: jsData.XBPitchMinThroughBelt });
    }
}
// 更新一般消息
function updateCM(jsData) {
    if (jsData == null || jsData == "" || jsData == undefined) {
        return;
    }
    else {
        var jdata = JSON.parse(jsData.Content);
        meta2d.setValue({ id: 'pitchMoveToValue', text: jdata.XBPitchAngle });
        meta2d.setValue({ id: 'rotateMoveToValue', text: jdata.XBRotationAngle });
        meta2d.setValue({ id: 'dcMoveToValue', text: jdata.DCPosition });
    }
}

// 连接WebSocket
function onConnectWebSocket() {
    if (m_NeptWebSocket == null) {
        m_NeptWebSocket = new NeptWebSocket(
            g_CenterServerIp,
            g_CenterWebSocketPort,
            g_WebSocketMaxReconnectInterval,
            updateView,
            "pid=" + g_PageID_Home
        );
    }
    m_NeptWebSocket.tryCreate();
}


// 故障详情
function onClickFaultDetail(){
    let url = "fault.html";
    myLayer = layer.open({
        type: 2,
        title: '故障详情',
        shadeClose: true, //点击遮罩关闭层
        area: ['1600px', '900px'],
        content: [url, 'no'],
    });
}


// 辅机控制
function onClickAuxiliary(){
    let url = "auxiliary.html";
    layer.open({
        type: 2,
        title: '辅机控制',
        shadeClose: true, //点击遮罩关闭层
        area: ['1300px', '600px'],
        content: [url, 'no'],
    });
}

// 保护设置
function onClickProtect(){
    let url = "protect.html";
    layer.open({
        type: 2,
        title: '保护设置',
        shadeClose: true, //点击遮罩关闭层
        area: ['1300px', '800px'],
        content: [url, 'no'],
    });
}

// 参数设置
function onClickParamSetting() {
    let url = "paramsSetting.html";
    layer.open({
        type: 2,
        title: '参数设置',
        shadeClose: false,
        area: ['1200px', '860px'],
        content: [url, 'no'],
    });
}